import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class MessageService {
    private messageObservables = new Map<string, any>();

    Send(messageName: string, message?: any) {
        this.getMessageObservable(messageName).next(message);
    }

    On(messageName: string, observerOrNext?: any) {
        return this.getMessageObservable(messageName).subscribe(observerOrNext);
    }

    Unsubscribe(messageName: string) {
        this.getMessageObservable(messageName).unsubscribe();
        this.messageObservables.delete(messageName)
    }

    getMessageObservable(messageName: string) {
        let messageObservable = this.messageObservables.get(messageName);
        if (!messageObservable) {
            messageObservable = new Subject();
            this.messageObservables.set(messageName, messageObservable);
        }
        return messageObservable;
    }
}
